package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import jdk.nashorn.internal.runtime.logging.Logger;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Service
@Logger
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserLoginService {
    @Override
    public ResponseResult login(LoginDTO dto) {
        //1.  参数校验  判断手机号 密码是否为空
        //  if  dto==null:
        if (StringUtils.isNotBlank(dto.getPhone())&& StringUtils.isNotBlank(dto.getPassword())) {
            //2.  手机号密码登录
            //2.1  手机号去查密码
            ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            //2.2  判断用户状态
//            if (!apUser.getFlag().equals("1")) {
//                throw new CustomException(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
//            }

            //2.3  检查数据库密码和输入的密码是否一致
            String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword()+apUser.getSalt()).getBytes(StandardCharsets.UTF_8));
            if (!newPwd.equals(apUser.getPassword())) {
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //2.4  一致 颁发token   返回 map： user  token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            HashMap<Object, Object> map = new HashMap<>();
            apUser.setPassword(null);
            apUser.setSalt(null);
            map.put("user",apUser);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }else {
            //3  手机号和密码为空   用设备 id  登录
            //3.1  颁发token   userid  为 0
            if (dto.getEquipmentId() == null) {
                throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"需要账户密码或者授权手机权限");
            }
            String token = AppJwtUtil.getToken(0L);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);

        }


    }
}
